<template>
  <div class="ansible-inventories">
    <div class="page-header">
      <h2>📋 配置管理 (Inventory)</h2>
      <button class="btn btn-primary" @click="showAddModal = true">+ 添加清单</button>
    </div>

    <div v-if="!inventories || inventories.length === 0" class="empty-state">
      <div class="empty-icon">📋</div>
      <p>暂无配置</p>
      <p class="empty-hint">点击右上角"添加清单"按钮创建Ansible配置</p>
    </div>

    <div class="inventory-grid" v-else>
      <div v-for="inv in inventories" :key="inv.id" class="inventory-card">
        <div class="card-header">
          <h3>{{ inv.name }}</h3>
          <div class="card-actions">
            <button class="btn btn-sm" @click="editInventory(inv)">编辑</button>
            <button class="btn btn-sm btn-danger" @click="deleteInventory(inv.id)">删除</button>
          </div>
        </div>
        <div class="card-body">
          <div class="info-row">
            <span class="label">主机地址:</span>
            <span class="value">{{ inv.host_address }}</span>
          </div>
          <div class="info-row">
            <span class="label">SSH端口:</span>
            <span class="value">{{ inv.ssh_port }}</span>
          </div>
          <div class="info-row">
            <span class="label">用户名:</span>
            <span class="value">{{ inv.ssh_user }}</span>
          </div>
          <div class="info-row">
            <span class="label">认证方式:</span>
            <span class="value">{{ getAuthTypeText(inv.auth_type) }}</span>
          </div>
          <div class="info-row">
            <span class="label">Ansible配置:</span>
            <span class="value small">{{ inv.ansible_config_path }}</span>
          </div>
          <div class="info-row">
            <span class="label">关联主机:</span>
            <span class="value">
              <span class="host-count-badge">{{ inv.host_count || 0 }}台</span>
            </span>
          </div>
          <div class="info-row">
            <span class="label">状态:</span>
            <span class="value">
              <span class="status-badge" :class="{ active: inv.is_enabled }">
                {{ inv.is_enabled ? '✅ 启用' : '❌ 禁用' }}
              </span>
              <span v-if="inv.is_default" class="status-badge default">⭐ 默认</span>
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑清单弹窗 -->
    <div v-if="showAddModal || showEditModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ showEditModal ? '编辑清单' : '添加清单' }}</h3>
          <button class="btn-close" @click="closeModal">✕</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveInventory">
            <div class="form-group">
              <label><span class="required">*</span> 配置名称</label>
              <input v-model="formData.name" required placeholder="请输入配置名称" />
            </div>
            
            <div class="form-group">
              <label>描述</label>
              <textarea v-model="formData.description" rows="2" placeholder="请输入配置描述"></textarea>
            </div>
            
            <div class="form-group">
              <label><span class="required">*</span> 主机地址</label>
              <input v-model="formData.host_address" required placeholder="localhost" />
            </div>
            
            <div class="form-group">
              <label><span class="required">*</span> SSH端口</label>
              <div class="port-input">
                <button type="button" class="port-btn" @click="decrementPort">-</button>
                <input type="number" v-model.number="formData.ssh_port" required min="1" max="65535" />
                <button type="button" class="port-btn" @click="incrementPort">+</button>
              </div>
            </div>
            
            <div class="form-group">
              <label><span class="required">*</span> 用户名</label>
              <input v-model="formData.ssh_user" required placeholder="SSH登录用户名" />
            </div>
            
            <div class="form-group">
              <label>认证方式</label>
              <div class="radio-group-horizontal">
                <label class="radio-item-horizontal">
                  <input type="radio" v-model="formData.auth_type" value="password" />
                  <span>密码认证</span>
                </label>
                <label class="radio-item-horizontal">
                  <input type="radio" v-model="formData.auth_type" value="key" />
                  <span>密钥认证</span>
                </label>
              </div>
            </div>
            
            <!-- 密码认证 -->
            <div v-if="formData.auth_type === 'password'" class="form-group">
              <label>密码</label>
              <input type="password" v-model="formData.ssh_password" placeholder="SSH登录密码" />
            </div>
            
            <!-- 密钥认证 -->
            <div v-if="formData.auth_type === 'key'" class="form-group">
              <label>SSH密钥</label>
              <textarea v-model="formData.ssh_key" rows="4" 
                placeholder="-----BEGIN RSA PRIVATE KEY-----&#10;...&#10;-----END RSA PRIVATE KEY-----"></textarea>
            </div>
            
            <div class="form-group">
              <label>Ansible配置路径</label>
              <input v-model="formData.ansible_config_path" placeholder="/etc/ansible/ansible.cfg" />
            </div>
            
            <div class="form-group">
              <label>Inventory路径</label>
              <input v-model="formData.inventory_path" placeholder="/etc/ansible/hosts" />
            </div>
            
            <div class="form-group">
              <label>关联主机</label>
              <div class="host-selector">
                <div class="host-selector-header">
                  <span>选择要关联到此清单的主机 (已选 {{ formData.hosts.length }} 台)</span>
                  <button type="button" class="btn-link" @click="selectAllHosts">
                    {{ formData.hosts.length === hosts.length ? '取消全选' : '全选' }}
                  </button>
                </div>
                <div class="host-list">
                  <label v-for="host in hosts" :key="host.id" class="host-item">
                    <input 
                      type="checkbox" 
                      :value="host.id" 
                      v-model="formData.hosts"
                    />
                    <span class="host-info">
                      <span class="host-name">{{ host.name }}</span>
                      <span class="host-ip">{{ host.ip }}</span>
                    </span>
                  </label>
                  <div v-if="hosts.length === 0" class="empty-hosts">
                    <p>暂无可用主机</p>
                    <p class="hint">请先在"主机管理"页面添加主机</p>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="form-group">
              <label>状态设置</label>
              <div class="checkbox-group">
                <label class="checkbox-item">
                  <input type="checkbox" v-model="formData.is_enabled" />
                  <span>启用此配置</span>
                </label>
                <label class="checkbox-item">
                  <input type="checkbox" v-model="formData.is_default" />
                  <span>设为默认配置</span>
                </label>
              </div>
            </div>
            
            <div class="form-actions">
              <button type="button" class="btn" @click="closeModal">取消</button>
              <button type="submit" class="btn btn-primary">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import api from '../services/api'

const inventories = ref([])
const hosts = ref([])
const showAddModal = ref(false)
const showEditModal = ref(false)
const formData = ref({
  name: '',
  description: '',
  host_address: 'localhost',
  ssh_port: 22,
  ssh_user: 'root',
  auth_type: 'password',
  ssh_password: '',
  ssh_key: '',
  ansible_config_path: '/etc/ansible/ansible.cfg',
  inventory_path: '/etc/ansible/hosts',
  is_enabled: true,
  is_default: false,
  hosts: []
})

const loadData = async () => {
  try {
    const [invData, hostData] = await Promise.all([
      api.getInventories(),
      api.getHosts()
    ])
    inventories.value = Array.isArray(invData) ? invData : (invData.results || [])
    hosts.value = Array.isArray(hostData) ? hostData : (hostData.results || [])
    console.log('加载成功，清单数量:', inventories.value.length)
  } catch (error) {
    console.error('加载数据失败:', error)
    inventories.value = []
    hosts.value = []
  }
}

const getAuthTypeText = (type) => {
  return type === 'password' ? '🔐 密码' : '🔑 密钥'
}

const incrementPort = () => {
  if (formData.value.ssh_port < 65535) {
    formData.value.ssh_port++
  }
}

const decrementPort = () => {
  if (formData.value.ssh_port > 1) {
    formData.value.ssh_port--
  }
}

const editInventory = (inv) => {
  formData.value = {
    id: inv.id,
    name: inv.name,
    description: inv.description,
    host_address: inv.host_address,
    ssh_port: inv.ssh_port,
    ssh_user: inv.ssh_user,
    auth_type: inv.auth_type,
    ssh_password: '',
    ssh_key: '',
    ansible_config_path: inv.ansible_config_path,
    inventory_path: inv.inventory_path,
    is_enabled: inv.is_enabled,
    is_default: inv.is_default,
    hosts: inv.hosts || []
  }
  showEditModal.value = true
}

const saveInventory = async () => {
  try {
    const data = { ...formData.value }
    
    // 清理不需要的字段
    if (data.auth_type === 'password') {
      delete data.ssh_key
    } else if (data.auth_type === 'key') {
      delete data.ssh_password
    }
    
    if (showEditModal.value) {
      await api.updateInventory(data.id, data)
      console.log('更新成功')
    } else {
      await api.createInventory(data)
      console.log('添加成功')
    }
    closeModal()
    loadData()
  } catch (error) {
    console.error('保存失败:', error.response?.data?.error || error.response?.data?.detail || error.message)
  }
}

const deleteInventory = async (id) => {
  if (!confirm('确定要删除这个清单吗？')) return
  try {
    await api.deleteInventory(id)
    console.log('删除成功')
    loadData()
  } catch (error) {
    console.error('删除失败:', error.response?.data?.error || error.message)
  }
}

const selectAllHosts = () => {
  if (formData.value.hosts.length === hosts.value.length) {
    formData.value.hosts = []
  } else {
    formData.value.hosts = hosts.value.map(h => h.id)
  }
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  formData.value = {
    name: '',
    description: '',
    host_address: 'localhost',
    ssh_port: 22,
    ssh_user: 'root',
    auth_type: 'password',
    ssh_password: '',
    ssh_key: '',
    ansible_config_path: '/etc/ansible/ansible.cfg',
    inventory_path: '/etc/ansible/hosts',
    is_enabled: true,
    is_default: false,
    hosts: []
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
@import '../styles/ansible-theme.css';

/* 主机选择器样式 */
.host-selector {
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  background: rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

.host-selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: rgba(255, 70, 85, 0.1);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.host-selector-header span {
  color: var(--color-text-primary);
  font-weight: 600;
  font-size: 14px;
}

.btn-link {
  background: none;
  border: none;
  color: var(--color-accent-cyan);
  cursor: pointer;
  font-size: 13px;
  font-weight: 600;
  padding: 4px 8px;
  transition: all 0.3s;
}

.btn-link:hover {
  color: #fff;
  text-decoration: underline;
}

.host-list {
  max-height: 300px;
  overflow-y: auto;
  padding: 8px;
}

.host-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 12px;
  margin-bottom: 6px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.host-item:hover {
  background: rgba(0, 255, 200, 0.1);
  border-color: var(--color-accent-cyan);
  transform: translateX(4px);
}

.host-item input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
  accent-color: var(--color-accent-cyan);
}

.host-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
}

.host-name {
  color: var(--color-text-primary);
  font-weight: 600;
  font-size: 14px;
}

.host-ip {
  color: var(--color-text-secondary);
  font-size: 12px;
  font-family: monospace;
}

.empty-hosts {
  text-align: center;
  padding: 40px 20px;
  color: var(--color-text-secondary);
}

.empty-hosts p {
  margin: 8px 0;
}

.empty-hosts .hint {
  font-size: 12px;
  color: var(--color-accent-red);
}

/* 主机数量徽章 */
.host-count-badge {
  display: inline-block;
  padding: 4px 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px;
  font-size: 13px;
  font-weight: 600;
  white-space: nowrap;
}
</style>
